const { exec, escape } = require('../db/mysql');
const xss = require('xss');

const getList = (author, keyword) => {
  // 这里加上 1=1 是为了防止 author 和 keyword 都不存在
  let sql = `select * from blogs where 1=1 `;
  if (author) sql += `and author=${author} `;
  if (keyword) sql += `and title like '%${keyword}%' `;
  sql += `order by createtime desc`;
  return exec(sql);
}

const getDetail = (id) => {
  let sql = `select * from blogs where 1=1 `;
  if (id) sql += `and id=${id}`;
  return exec(sql);
}

const newBlog = (blogData = {}) => {
  let { title, content, author } = blogData;
  console.log(content);
  title = xss(title);
  content = xss(content);
  console.log(content);
  const createTime = Date.now();
  let sql = `insert into blogs (title, content, createtime, author)
    values ('${title}', '${content}', ${createTime}, '${author}')
  `;
  return exec(sql);
}

const updateBlog = (id, blogData = {}) => {
  const { title, content } = blogData;
  let sql = `update blogs set title='${title}', content='${content}' where id=${id}`;
  return exec(sql);
}

const delBlog = (id, author) => {
  if (!id) return;
  let sql = `delete from blogs where id=${id} and author='${author}'`;
  return exec(sql);
}

module.exports = {
  getList,
  getDetail,
  updateBlog,
  newBlog,
  delBlog
}
